package com.sweet.util;

import lombok.Data;

import java.text.NumberFormat;

/**
 * jvm工具
 *
 * @author limi
 * @date 2019/5/17 15:09
 */
public class JvmUtil {
    /**
     * 获取占用内存总数
     *
     * @return
     */
    public static double getTotalMemory() {
        return Runtime.getRuntime().totalMemory() / 1024 / 1024;
    }

    /**
     * 获取最大可用内存
     *
     * @return
     */
    public static double getMaxMemory() {
        return Runtime.getRuntime().maxMemory() / 1024 / 1024;
    }

    /**
     * 获取空闲内存总数
     *
     * @return
     */
    public static double getFreeMemory() {
        return Runtime.getRuntime().freeMemory() / 1024 / 1024;
    }

    /**
     * 获取jvm内存
     *
     * @return
     */
    public static JvmVO getMemory() {
        //保留3位小数
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(3);
        numberFormat.setGroupingUsed(false);

        //定义jvm内存
        JvmVO jvm = new JvmVO();
        jvm.setTotal(getTotalMemory());
        jvm.setMax(getMaxMemory());
        jvm.setFree(getFreeMemory());

        return jvm;
    }

    @Data
    private static class JvmVO {
        private double total;    //程序占用内存总数
        private double max;      //jvm最大可用内存
        private double free;     //空闲内存总数
        private double unused;   //实际可用内存

        public double getUnused() {
            return this.max - this.total + this.free;
        }
    }
}